package com.server.llh.llhserverwork.activity.server;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.BaseLeLaohuiAcitivity;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.adapter.LLHServerCateContentAdapter;
import com.server.llh.llhserverwork.adapter.LLHShoppingServerAdapter;
import com.server.llh.llhserverwork.adapter.ServerMenuAdapter;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.ProCateService;
import com.server.llh.llhserverwork.bean.SerInitProPackage;
import com.server.llh.llhserverwork.bean.ShowProInfoBean;
import com.server.llh.llhserverwork.port.ClearViewDataInterface;
import com.server.llh.llhserverwork.port.OrderServerInterface;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.ServerStatementData;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.ShopUploadParamJson;
import com.server.llh.llhserverwork.utils.ShoppingServerCar;
import com.server.llh.llhserverwork.view.MyPopupWindow;
import com.server.llh.llhserverwork.view.ShowProInfoView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LlhServerMenuTwoActivity extends BaseLeLaohuiAcitivity implements OrderServerInterface, ClearViewDataInterface {
    @BindView(R.id.title_view)
    LinearLayout titleView;
    @BindView(R.id.menu_two_lv)
    ListView menuTwoLv;
    @BindView(R.id.menu_content_lv)
    ListView menuContentLv;
    @BindView(R.id.noDataSrc)
    ImageView noDataSrc;
    @BindView(R.id.reloadbt)
    ImageView reloadbt;
    @BindView(R.id.center)
    LinearLayout center;
    @BindView(R.id.center_view)
    LinearLayout centerView;
    @BindView(R.id.shop_car_total_msg)
    TextView shopCarTotalMsg;
    @BindView(R.id.shop_car_commit)
    Button shopCarCommit;
    @BindView(R.id.msg_toast)
    ImageView msgToast;
    @BindView(R.id.food_num)
    TextView proNum;
    @BindView(R.id.shop_car_layout)
    RelativeLayout shopCarLayout;
    @BindView(R.id.buttom_view)
    LinearLayout buttomView;
    @BindView(R.id.shop_main)
    RelativeLayout shopMain;
    @BindView(R.id.main_img)
    ImageView main_img;
    private final static String TAG = "MenuTwo";
    private String mCateId, mCateName, mIsPack;
    private String orgId, chainId, orgTypeId, userId;
    private LLHShoppingServerAdapter llhShoppingServerAdapter = null;
    private List<SerInitProPackage> serviceInitProPack = new ArrayList<SerInitProPackage>();//服务项显示数据
    private ArrayList<SerInitProPackage> shopping_car_List = new ArrayList<>();//购物车显示list数据
    ImageButton leftBtn;
    TextView titlebarText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        chainId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.CHAIN_ID, getApplicationContext());
        orgTypeId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE, getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID, getApplicationContext());
        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID, getApplicationContext());
        LlhShopingOrderActivity.registCallBack(this);
        leftBtn = (ImageButton) findViewById(R.id.main_back);
        leftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        titlebarText = (TextView) findViewById(R.id.titleName);
        Intent intent = getIntent();
        if (intent != null) {
            mCateName = intent.getStringExtra("cateName");
            mCateId = intent.getStringExtra("cateId");
            mIsPack = intent.getStringExtra("mIsPack");
            titlebarText.setText(mCateName);
        }
        buttomView.setVisibility(View.VISIBLE);
        menuTwoLv.setVisibility(View.GONE);
        menuContentLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (serviceInitProPack.get(position) != null) {
                    ShowProInfoBean showProInfoBean = new ShowProInfoBean(serviceInitProPack.get(position).getPictureUrl(),
                            serviceInitProPack.get(position).getPrice(), serviceInitProPack.get(position).getPackName(),
                            serviceInitProPack.get(position).getReamark(), "100%");
                    ShowProInfoView.showProInfo(showProInfoBean, LlhServerMenuTwoActivity.this.findViewById(R.id.shop_main), LlhServerMenuTwoActivity.this);
                }
            }
        });

        initShopingCarView();
        reqServerMenu(mCateId, mIsPack);
    }
    @Override
    protected void doBasess() {

    }
    private RelativeLayout buy_list_Layout;
    TextView totle_price, delete_all;
    ListView buy_listView;
    public void initShopingCarView() {
        buy_list_Layout = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.shopping_list_layout, null);
        totle_price = (TextView) buy_list_Layout.findViewById(R.id.totle_price);
        delete_all = (TextView) buy_list_Layout.findViewById(R.id.delete_all);
        delete_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearShoppingCar();
            }
        });
        buy_listView = (ListView) buy_list_Layout.findViewById(R.id.food_listview);

        llhShoppingServerAdapter = new LLHShoppingServerAdapter();
        buy_listView.setAdapter(llhShoppingServerAdapter);
        llhShoppingServerAdapter.registerCallBack(this);
    }
    /**
     * 点击显示购物车popuwindow
     */
    private MyPopupWindow myPopupWindow = null;
    public void showShopProPopView() {
        if (shopping_car_List == null || shopping_car_List.size() == 0) {
            T.showAnimToast(getApplicationContext(), "抱歉，您还未选择服务！");
            return;
        } else if (shopping_car_List != null && shopping_car_List.size() > 0) {
            myPopupWindow = new MyPopupWindow(LlhServerMenuTwoActivity.this, buy_list_Layout);
            myPopupWindow.showAtLocation(LlhServerMenuTwoActivity.this.findViewById(R.id.shop_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            llhShoppingServerAdapter.setData(shopping_car_List);
        }
    }
    /**
     * 清除购物车所有商品
     */
    public void clearShoppingCar() {
        try {
            if (shopping_car_List!=null&&shopping_car_List.size()>0){
                for (int i = 0; i < shopping_car_List.size(); i++) {
                    SerInitProPackage foodModel = shopping_car_List.get(i);
                    foodModel.buyNum = 0;
                }
                llhServerCateContentAdapter.notifyDataSetChanged();
                shopping_car_List.clear();
                llhShoppingServerAdapter.notifyDataSetChanged();
                refreshShoppingList(null);
                if (myPopupWindow != null) {
                    myPopupWindow.dismiss();
                }
            }
        } catch (Exception E) {
            Log.d(TAG, "Exception==" + E.getMessage());
        }

    }
    @Override
    protected void onResume() {
        super.onResume();
//        reqServerMenu(mCateId,mIsPack);
//        reloadbt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                reloadbt.setVisibility(View.GONE);
//                reqServerMenu(mCateId,mIsPack);
//            }
//        });
    }
    private LLHServerCateContentAdapter llhServerCateContentAdapter = null;//右侧服务项adapter
    private ServerMenuAdapter llhServerAdapter = null;
    private List<ProCateService> service = new ArrayList<>();
    public void showProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    showProgress(LlhServerMenuTwoActivity.this);
                } catch (Exception e) {

                }
            }
        });
    }
    public void hideProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    closeProgress();
                } catch (Exception e) {

                }

            }
        });
    }
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }
    @Override
    protected void initView() {

    }
    @OnClick({R.id.main_img, R.id.shop_car_commit, R.id.msg_toast, R.id.shop_car_layout, R.id.buttom_view})
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.image_break:
//                onBackPressed();
//                break;

            case R.id.shop_car_commit:
//                T.showAnimToast(getApplicationContext(),"啦啦啦啦啦啦啦。。。"+shopping_car_List.size());
                if (shopping_car_List != null && shopping_car_List.size() > 0) {
                    reqServerShopUpload(shopping_car_List);
                }
                break;
            case R.id.msg_toast:
                showShopProPopView();
                break;
            case R.id.shop_car_layout:
                break;
            case R.id.buttom_view:
                break;
            case R.id.main_img:
                Intent intent = new Intent();
                intent.setAction(Constants.BroadCastAction.FINISH_ALL_ACTIVITY);
                sendBroadcast(intent);
                onBackPressed();
                break;
        }
    }
    protected int getlayout() {
        return R.layout.activity_server_menu_two;
    }
    @Override
    public void callBack() {
    }
    private String moneyConunt;
    @Override
    public void refreshShoppingList(SerInitProPackage serInitProPackage) {
        int num = ShoppingServerCar.getShopingData(serInitProPackage, shopping_car_List);
        proNum.setText("" + num);
        if (shopping_car_List.size() > 0 && num > 0) {
            buttomView.setVisibility(View.VISIBLE);
            double totlepeice = 0;
            for (int i = 0; i < shopping_car_List.size(); i++) {
                SerInitProPackage tempServerModel = shopping_car_List.get(i);
                totlepeice = totlepeice + tempServerModel.price
                        * tempServerModel.buyNum;
            }
            double d = totlepeice;
            String result = String.format("%.2f", d);
            shopCarTotalMsg.setText("合计：" + result + "元");
            totle_price.setText("合计：" + result + "元");
            moneyConunt = result;
        } else {
            buttomView.setVisibility(View.VISIBLE);
            shopCarTotalMsg.setVisibility(View.VISIBLE);
            shopCarTotalMsg.setText("请为老人选择服务");
            totle_price.setText("合计：0元");
            if (myPopupWindow != null && myPopupWindow.isShowing()) {
                myPopupWindow.dismiss();
            }
        }
        llhShoppingServerAdapter.setData(shopping_car_List);
    }
    @Override
    public void refreshFoodList() {
        llhServerCateContentAdapter.notifyDataSetChanged();
    }
    /**
     * 服务二级分类请求
     * @param mCateId
     * @param mIsPack
     */
    private void reqServerMenu(final String mCateId, final String mIsPack) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("cateLevel", 1);
        lRequest.addParam("parendId", mCateId);
        lRequest.addParam("cateId", mCateId);
        lRequest.addParam("packorgId", SharedPreferenceUtil.getUserInfo(Constants.UserInfo.CHAIN_ID, getApplicationContext()));
        lRequest.addParam("packorgTypeId", 3);
        lRequest.addParam("isPack", mIsPack);
        lRequest.addParam("isEmptyShow", Constants.IS_EMPTY_SHOW_INT);
        lRequest.addParam("packStatus", Constants.PACK_STATUS_INT);
        lRequest.setUri(ServerPort.GET_SERVER_ON_TYPE);
        lRequest.setIp(UrlsTools.SERVER_REQ_URL);
        lRequest.setType(String.class);

        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                reloadbt.setVisibility(View.GONE);
                T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
            }
            @Override
            public void onNext(String responseBean, String code) {
                if ("200".equals(code) && !"[]".equals(responseBean) && responseBean != null) {
                    service = new Gson().fromJson(responseBean.toString(),
                            new TypeToken<List<ProCateService>>() {
                            }.getType());
                    if (service != null && service.size() > 0) {
                        reloadbt.setVisibility(View.GONE);
                        centerView.setVisibility(View.VISIBLE);
                        menuTwoLv.setVisibility(View.VISIBLE);
                        llhServerAdapter = new ServerMenuAdapter(getApplicationContext(), service);
                        menuTwoLv.setAdapter(llhServerAdapter);
                        menuTwoLv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                reloadbt.setVisibility(View.GONE);
                                menuTwoLv.setSelected(true);
                                menuTwoLv.setSelection(0);
                                menuTwoLv.setItemChecked(0, true);
                                menuTwoLv.performItemClick(menuTwoLv.getChildAt(0), 0, 0);
                            }
                        }, 500);
                    } else {
                        reloadbt.setVisibility(View.VISIBLE);
                    }
                } else {
                    reloadbt.setVisibility(View.VISIBLE);
                }
            }
        });
        menuTwoLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                clearShoppingCar();
                long mCateId = service.get(position).getCateId();
                int mIsPack = service.get(position).getIsPack();
                reqServerCateMenu(mCateId, mIsPack);
            }
        });
    }
    /**
     * 服务项请求
     * @param mCateId
     * @param mIsPack
     */
    public void reqServerCateMenu(long mCateId, int mIsPack) {
        LRequest lRequest = new LRequest();
        if (mIsPack == 1) {
            lRequest.addParam("serviceCateId", mCateId);
        } else {
            lRequest.addParam("detailCateId", mCateId);
        }
        if ("3".equals(orgTypeId)) {
            lRequest.addParam("orgId", orgId);
            lRequest.addParam("orgTypeId", orgTypeId);
        } else {
            lRequest.addParam("orgId", chainId);
            lRequest.addParam("orgTypeId", "3");
            lRequest.addParam("supplierId", orgId);
            lRequest.addParam("supplierType", "4");
        }
        lRequest.setUri(ServerPort.SERVER_JSON_DATA);
        lRequest.setIp(UrlsTools.SERVER_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                reloadbt.setVisibility(View.VISIBLE);
                T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null && Constants.SER_RESPON_SUCC_CODE.equals(code)) {
                    serviceInitProPack = new Gson().fromJson(
                            responseBean.toString(),
                            new TypeToken<List<SerInitProPackage>>() {
                            }.getType());
                    if (serviceInitProPack != null && serviceInitProPack.size() > 0) {

                        menuContentLv.setVisibility(View.VISIBLE);
                        if (menuContentLv.getAdapter() == null) {
                            llhServerCateContentAdapter = new LLHServerCateContentAdapter(getApplicationContext(), serviceInitProPack);
                            menuContentLv.setAdapter(llhServerCateContentAdapter);
                            llhServerCateContentAdapter.registerCallBack(LlhServerMenuTwoActivity.this);
                        } else {
                            llhServerCateContentAdapter.setListData(serviceInitProPack);
                            llhServerCateContentAdapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    T.showAnimToast(getApplicationContext(), "抱歉，暂时没有该服务！");
                }
            }
        });


    }
    /**
     * 提交购物车数据
     * @param serInitProPackageList
     */
    public static ServerStatementData serverStatementData;
    public void reqServerShopUpload(List<SerInitProPackage> serInitProPackageList) {
        String reqServerParamJson = ShopUploadParamJson.reqServerParamJson(serInitProPackageList);
        try {
            reqServerParamJson = URLEncoder.encode(reqServerParamJson, "utf-8");
            LRequest lRequest = new LRequest();
            lRequest.addParam("userId", userId);
            lRequest.addParam("serOrderInfoDetailList", reqServerParamJson);
            lRequest.addParam("orgId", orgId);
            lRequest.addParam("orgTypeId", orgTypeId);
            lRequest.addParam("cateLevel", Constants.CATE_LEVEL_INT);
            lRequest.setUri(ServerPort.SERVER_CAL_ORDER_MONEY);
            lRequest.setIp(UrlsTools.SERVER_REQ_URL);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null && Constants.SER_RESPON_SUCC_CODE.equals(code)) {
                        Log.d(TAG, "responseBean==" + responseBean.toString());
                        serverStatementData = new Gson().fromJson(responseBean.toString(), ServerStatementData.class);
                        if (serverStatementData != null) {
                            Log.d(TAG, "serverStatementData==" + serverStatementData.getSerOrderInfo().getAmountPayable());
                            Intent intent = new Intent(getApplicationContext(), LlhShopingOrderActivity.class);
                            startActivity(intent);
                        }
                    } else {
                        T.showAnimToast(getApplicationContext(), "暂时没有服务信息！");
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void clearShopData(String succ) {
        if ("0".equals(succ)) {
            clearShoppingCar();
        } else {
            Intent intent = new Intent();
            intent.setAction(Constants.BroadCastAction.FINISH_ALL_ACTIVITY);
            sendBroadcast(intent);
            finish();
        }

    }
    @Override
    public void refreshData() {

    }
}